import { createApp, h } from 'vue';
import ErrorNotification from '@/components/ErrorNotification.vue';
import { 
  handleAppError, 
  setupGlobalErrorHandlers,
  getUserFriendlyErrorMessage 
} from '@/utils/errorHandler';

// 创建通知容器
let notificationContainer = null;
let notificationApp = null;
let currentNotification = null;

/**
 * 初始化通知容器
 */
function initNotificationContainer() {
  // 如果已经存在，先移除
  if (notificationContainer) {
    document.body.removeChild(notificationContainer);
  }
  
  // 创建新的容器
  notificationContainer = document.createElement('div');
  notificationContainer.id = 'error-notification-container';
  document.body.appendChild(notificationContainer);
  
  // 创建Vue应用
  notificationApp = createApp({
    data() {
      return {
        error: null,
        message: '',
        type: 'error',
        position: 'top-right',
        duration: 5000,
        closable: true
      };
    },
    methods: {
      handleClose() {
        this.error = null;
        this.message = '';
      }
    },
    render() {
      return h(ErrorNotification, {
        error: this.error,
        message: this.message,
        type: this.type,
        position: this.position,
        duration: this.duration,
        closable: this.closable,
        onClose: this.handleClose
      });
    }
  });
  
  // 挂载应用
  currentNotification = notificationApp.mount(notificationContainer);
}

/**
 * 显示错误通知
 * @param {Object|String} error - 错误对象或错误消息
 * @param {Object} options - 配置选项
 */
function showErrorNotification(error, options = {}) {
  // 确保容器已初始化
  if (!notificationContainer || !currentNotification) {
    try {
      initNotificationContainer();
    } catch (e) {
      console.error('初始化错误通知容器失败:', e);
      return;
    }
  }
  
  // 设置错误信息
  try {
    if (typeof error === 'string') {
      currentNotification.message = error;
      currentNotification.error = null;
    } else {
      currentNotification.error = error;
      currentNotification.message = error?.message || '发生未知错误';
    }
    
    // 应用选项
    if (options.type) currentNotification.type = options.type;
    if (options.position) currentNotification.position = options.position;
    if (options.duration !== undefined) currentNotification.duration = options.duration;
    if (options.closable !== undefined) currentNotification.closable = options.closable;
  } catch (e) {
    console.error('设置错误通知内容失败:', e);
  }
}

/**
 * Vue错误处理插件
 */
export default {
  install: (app, options = {}) => {
    // 初始化通知容器
    initNotificationContainer();
    
    // 设置全局错误处理
    setupGlobalErrorHandlers();
    
    // 全局错误处理方法
    app.config.errorHandler = (error, instance, info) => {
      console.error('Vue Error:', error);
      
      // 处理错误
      const appError = handleAppError(error, { 
        componentName: instance?.$options?.name || 'Unknown',
        info 
      });
      
      // 显示错误通知
      if (options.showNotification !== false) {
        showErrorNotification(appError);
      }
      
      // 调用用户自定义处理方法
      if (typeof options.onError === 'function') {
        options.onError(appError, instance, info);
      }
    };
    
    // 添加全局属性
    app.config.globalProperties.$errorHandler = {
      showError: (error, options) => showErrorNotification(error, options),
      getUserFriendlyMessage: getUserFriendlyErrorMessage
    };
    
    // 添加全局指令
    app.directive('error-handler', {
      mounted(el, binding) {
        const errorMessage = binding.value;
        if (errorMessage) {
          el.classList.add('has-error');
          
          // 创建错误提示元素
          const errorEl = document.createElement('div');
          errorEl.className = 'error-message';
          errorEl.textContent = errorMessage;
          
          // 添加到元素后面
          el.parentNode.insertBefore(errorEl, el.nextSibling);
        }
      },
      updated(el, binding) {
        // 移除旧的错误提示
        const oldError = el.nextElementSibling;
        if (oldError && oldError.className === 'error-message') {
          oldError.parentNode.removeChild(oldError);
        }
        
        el.classList.remove('has-error');
        
        // 添加新的错误提示
        const errorMessage = binding.value;
        if (errorMessage) {
          el.classList.add('has-error');
          
          const errorEl = document.createElement('div');
          errorEl.className = 'error-message';
          errorEl.textContent = errorMessage;
          
          el.parentNode.insertBefore(errorEl, el.nextSibling);
        }
      }
    });
    
    // 提供全局方法
    app.provide('errorHandler', {
      showError: (error, options) => showErrorNotification(error, options),
      getUserFriendlyMessage: getUserFriendlyErrorMessage
    });
  }
}; 